﻿// ===============================================================================
// 作者:吕艳阳
// 日期:2016-12-23 10:16
// 描述:
// 开发框架 版权所有
// ===============================================================================

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.IO;
using DotNet.Configuration;
using DotNet.Data;
using DotNet.Extensions;
using DotNet.Helper;

namespace BusRealtime
{
    /// <summary>
    /// 接收公交实时数据
    /// </summary>
    public class ReceiveRealBus
    {

        private int replayCount;

        /// <summary>
        /// Socket连接对象
        /// </summary>
        private Socket socket;

        /// <summary>
        /// IP地址
        /// </summary>
        private readonly string ip;

        /// <summary>
        /// 端口
        /// </summary>
        private readonly int port;

        /// <summary>
        /// 间隔毫秒数
        /// </summary>
        private readonly int interval;

        /// <summary>
        /// 总共处理的记录数
        /// </summary>
        private long processTotals;

        /// <summary>
        /// 是否运行,设为false则退出运行
        /// </summary>
        public bool IsRun { get; set; }

        /// <summary>
        /// 构造函数
        /// </summary>
        public ReceiveRealBus()
        {
            ip = ConfigManager.GetAppValue("IP");
            port = ConfigManager.GetAppValue("Port").ToInt();
            interval = ConfigManager.GetAppValue("Interval").ToInt();
            if (ip.IsEmpty())
            {
                throw new ApplicationException("请在配置文件中指定服务器的IP地址");
            }
            if (port <= 0)
            {
                throw new ApplicationException("请在配置文件中指定服务器的端口");
            }
            if (interval <= 0)
            {
                throw new ApplicationException("请在配置文件中指定轮训时间间隔");
            }
            Console.ResetColor();
            Console.WriteLine($"系统启动,读取配置文件:IP:{ip},端口:{port},间隔:{interval}ms");
            LogHelper.Log($"系统启动,读取配置文件:IP:{ip},端口:{port},间隔:{interval}ms");
        }

        /// <summary>
        /// 开始接收公交实时数据(组件启动入口)
        /// </summary>
        public void Run()
        {
            IsRun = true;
            while (IsRun)
            {
                RunCore();
            }
        }

        /// <summary>
        /// 接收公交实时数据
        /// </summary>
        private void RunCore()
        {
            try
            {
                var isConnectioned = false;
                do
                {
                    isConnectioned = ConnectServer();
                    if (!isConnectioned)
                    {
                        Console.ResetColor();
                        Console.WriteLine($"{interval}毫秒后,重新开始连接...");
                        LogHelper.Log($"{interval}毫秒后,重新开始连接...");
                        Thread.Sleep(interval);
                    }
                }
                while (!isConnectioned);
                Console.Write("读取网络数据");
                var netList = new List<string>();
                while (true)
                {
                    //if (DateTime.Now.Second % 3 != 0) continue;
                    try
                    {
                        Console.ResetColor();
                        //LogHelper.Log("准备读取网络数据");
                        var buffer = new byte[1024];
                        var receiveLength = socket.Receive(buffer);
                        var receiveString = Encoding.ASCII.GetString(buffer, 0, receiveLength);
                        Log(receiveString);
                        // LogHelper.Log($"报文:{receiveString}");
                        //Console.WriteLine($"报文:{receiveString}");
                        netList = receiveString.Split('\n').Where(a => a.Split(',').Length > 25).ToList();

                        //LogHelper.Log($"读取网络数据成功,共{netList.Count}条");
                        Console.Write($"{netList.Count},");
                        LogHelper.Log($"{netList.Count},");
                        if (netList.Count == 0)
                        {
                            replayCount++;
                            Thread.Sleep(200);
                        }
                        if (replayCount >= 1000)
                        {
                            LogHelper.Log($"1000次没有获取到数据,准备重连服务器");
                            Console.WriteLine("1000次没有获取到数据,准备重连服务器");
                            break;
                        }
                    }
                    catch (SocketException e)
                    {
                        Console.ForegroundColor = ConsoleColor.DarkYellow;
                        Console.WriteLine($"读取网络数据超时,原因:{e.Message}");
                        LogHelper.Log($"读取网络数据超时,原因:{e.Message}");
                        //Thread.Sleep(5000);
                        break;
                    }
                    catch (Exception e)
                    {
                        Console.ForegroundColor = ConsoleColor.Red;
                        Console.WriteLine($"读取网络数据失败,原因:{e.Message}");
                        LogHelper.Log($"读取网络数据失败,原因:{e.Message}");
                        break;
                    }
                    for (var index = 0; index < netList.Count; index++)
                    {
                        //LogHelper.Log($"准备入库第{index + 1}条");
                        var item = netList[index];

                        ExecuteToDatabase(item.Split(','));
                    }

                }
            }
            catch (Exception exx)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine($"执行失败,原因:{exx.Message}");
                LogHelper.Log($"执行失败,原因:{exx.Message}");
            }
            finally
            {
                try
                {
                    socket.Disconnect(true);
                    socket.Dispose();
                }
                catch (Exception exc)
                {
                    Console.WriteLine($"socket.Dispose失败,原因:{exc.Message}");
                    LogHelper.Log($"socket.Dispose失败,原因:{exc.Message}");
                }
            }
        }

        /// <summary>
        /// 连接服务器
        /// </summary>
        /// <returns>连接成功返回true</returns>
        private bool ConnectServer()
        {
            replayCount = 0;
            LogHelper.Log("准备创建连接对象");
            socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            try
            {
                LogHelper.Log($"正在连接到服务器->{ip}:{port}");
                Console.Write($"正在连接到服务器->{ip}:{port}");
                socket.Connect(new IPEndPoint(IPAddress.Parse(ip), port));
                socket.ReceiveTimeout = 3000;
                LogHelper.Log($"服务器连接成功->{ip}:{port}");
                Console.Write($"服务器连接成功->{ip}:{port}");
                return true;
            }
            catch (Exception e)
            {
                Console.ResetColor();
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine($"服务器连接失败->{ip}:{port};原因:\n{e.Message}");
                LogHelper.Log($"服务器连接失败->{ip}:{port};原因:\n{e.Message}");
                return false;
            }
        }

        /// <summary>
        /// 写入数据到数据库
        /// </summary>
        /// <param name="array">读取到的数组</param>
        private void ExecuteToDatabase(string[] array)
        {
            processTotals++;

            var dzFlag = array[6].ToInt();//到站标识:1.到站 2.离站
            var busselfid = array[2];//车载机编号
            var stationindex = array[7]; //站点索引
            var cstype = array[24];//车次类型 4.上行 5.下行
            var createtime = DateTime.Now;//添加时间
            var carnum = busselfid;//车载机编号
            var xlnum = array[0]; //路线 Id
            var sj = array[11].ToDateTime();// 时间
            var zdnum = array[7]; //站点编号
            var dznum = dzFlag; //到站标识
            var fx = cstype;//上下行

            const string sql = @"begin delete from daolizhan where busselfid=@busselfid;
                                insert into daolizhan (busselfid, stationindex, cstype, createtime, carnum, xlnum, sj, zdnum, dznum, fx)
                                values (@busselfid, @stationindex, @cstype, @createtime, @carnum, @xlnum, @sj, @zdnum, @dznum, @fx); end;";
            try
            {
                Console.ResetColor();
                using (var db = new Database())
                {
                    db.Execute(sql, new { busselfid, stationindex, cstype, createtime, carnum, xlnum, sj, zdnum, dznum, fx });
                    //Console.WriteLine($"写入db成功,线路:{xlnum};到离站:{dzFlag};车载机编号:{busselfid};共处理记录数:{processTotals}条");
                    //LogHelper.Log($"写入db成功,线路:{xlnum};到离站:{dzFlag};车载机编号:{busselfid};共处理记录数:{processTotals}条");
                }
            }
            catch (Exception e)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine($"写入公交实时数据失败;原因:{e.Message}");
                LogHelper.Log($"写入公交实时数据失败;原因:{e.Message}");
            }
        }


        private static string GetLogPath(string name)
        {
            string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Log", $"tcp-{name}.log");
            var dir = new FileInfo(path).Directory?.FullName;
            if (!string.IsNullOrEmpty(dir))
            {
                Directory.CreateDirectory(dir);
            }
            return path;
        }

        /// <summary>
        /// 记录日志
        /// </summary>
        /// <param name="message">日志内容</param>
        public static void Log(string message)
        {
            //string folder = DirHelper.RootDirectory;
            string path = GetLogPath(DateTime.Now.ToString("yyyy-MM-dd")); //System.IO.Path.Combine(folder, "tcp.log");
            //FileHelper.CreateDirectoryByPath(path);

            try
            {
                string msg = $"{DateTimeHelper.FormatDateHasSecond(DateTime.Now)} -> {message}";
                StreamWriter streamWriter = !File.Exists(path) ? File.CreateText(path) : File.AppendText(path);
                using (streamWriter)
                {
                    streamWriter.WriteLine(msg);
                    streamWriter.Flush();
                }
            }
            catch (Exception e)
            {
                DebugHelper.Debug(e.Message);
            }
        }
    }
}